#include "stm32f429xx.h"
/* 由于正点原子核心板扩展的SDRAM和NAND FLASH与官方差异较大,在Bsp中实现 */

#if !defined  (HSE_VALUE) 
  #define HSE_VALUE    ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */
#endif /* HSE_VALUE */

#if !defined  (HSI_VALUE)
  #define HSI_VALUE    ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */

/* Note: Following vector table addresses must be defined in line with linker
         configuration. */
/*!< Uncomment the following line if you need to relocate the vector table
     anywhere in Flash or Sram, else the vector table is kept at the automatic
     remap of boot address selected */
/* #define USER_VECT_TAB_ADDRESS */

#if defined(USER_VECT_TAB_ADDRESS)
/*!< Uncomment the following line if you need to relocate your vector Table
     in Sram else user remap will be done in Flash. */
/* #define VECT_TAB_SRAM */
#if defined(VECT_TAB_SRAM)
#define VECT_TAB_BASE_ADDRESS   SRAM_BASE       /*!< Vector Table base address field.
                                                     This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET         0x00000000U     /*!< Vector Table base offset field.
                                                     This value must be a multiple of 0x200. */
#else
#define VECT_TAB_BASE_ADDRESS   FLASH_BASE      /*!< Vector Table base address field.
                                                     This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET         0x00000000U     /*!< Vector Table base offset field.
                                                     This value must be a multiple of 0x200. */
#endif /* VECT_TAB_SRAM */
#endif /* USER_VECT_TAB_ADDRESS */
/******************************************************************************/

#define HSE_STARTUP_TIMEOUT 60000 // HSE启动超时
#define PLL_STARTUP_TIMEOUT 60000 // PLL启动超时
#define PLL_M 25  // HSE输入分频因子
#define PLL_N 336 // PLL倍频因子
#define PLL_P 2   // PLL输出分频因子
#define PLL_Q 7


/** @addtogroup STM32F4xx_System_Private_Variables
  * @{
  */
  /* This variable is updated in three ways:
      1) by calling CMSIS function SystemCoreClockUpdate()
      2) by calling HAL API function HAL_RCC_GetHCLKFreq()
      3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency 
         Note: If you use this function to configure the system clock; then there
               is no need to call the 2 first functions listed above, since SystemCoreClock
               variable is updated automatically.
  */
uint32_t SystemCoreClock = 16000000;
const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8]  = {0, 0, 0, 0, 1, 2, 3, 4};


/**
   * @brief  Update SystemCoreClock variable according to Clock Register Values.
  *         The SystemCoreClock variable contains the core clock (HCLK), it can
  *         be used by the user application to setup the SysTick timer or configure
  *         other parameters.
  *           
  * @note   Each time the core clock (HCLK) changes, this function must be called
  *         to update SystemCoreClock variable value. Otherwise, any configuration
  *         based on this variable will be incorrect.         
  *     
  * @note   - The system frequency computed by this function is not the real 
  *           frequency in the chip. It is calculated based on the predefined 
  *           constant and the selected clock source:
  *             
  *           - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
  *                                              
  *           - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
  *                          
  *           - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) 
  *             or HSI_VALUE(*) multiplied/divided by the PLL factors.
  *         
  *         (*) HSI_VALUE is a constant defined in stm32f4xx_hal_conf.h file (default value
  *             16 MHz) but the real value may vary depending on the variations
  *             in voltage and temperature.   
  *    
  *         (**) HSE_VALUE is a constant defined in stm32f4xx_hal_conf.h file (its value
  *              depends on the application requirements), user has to ensure that HSE_VALUE
  *              is same as the real frequency of the crystal used. Otherwise, this function
  *              may have wrong result.
  *                
  *         - The result of this function could be not correct when using fractional
  *           value for HSE crystal.
  *     
  * @param  None
  * @retval None
  */
void SystemCoreClockUpdate(void) {
  uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2;
  
  /* Get SYSCLK source -------------------------------------------------------*/
  tmp = RCC->CFGR & RCC_CFGR_SWS;

  switch (tmp)
  {
    case 0x00:  /* HSI used as system clock source */
      SystemCoreClock = HSI_VALUE;
      break;
    case 0x04:  /* HSE used as system clock source */
      SystemCoreClock = HSE_VALUE;
      break;
    case 0x08:  /* PLL used as system clock source */

      /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N
         SYSCLK = PLL_VCO / PLL_P
         */    
      pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22;
      pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM;
      
      if (pllsource != 0)
      {
        /* HSE used as PLL clock source */
        pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
      }
      else
      {
        /* HSI used as PLL clock source */
        pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6);
      }

      pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2;
      SystemCoreClock = pllvco/pllp;
      break;
    default:
      SystemCoreClock = HSI_VALUE;
      break;
  }
  /* Compute HCLK frequency --------------------------------------------------*/
  /* Get HCLK prescaler */
  tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
  /* HCLK frequency */
  SystemCoreClock >>= tmp;
}

/**
  * @brief  Setup the microcontroller system clock and peripherals.
  *         This function initializes the FPU setting, vector table location, 
  *         External memory configuration, and sets up the system clock 
  *         using the PLL with HSE as the clock source.
  * @param  None
  * @retval None
  */
void SystemInit(void) {
  uint16_t timeout = 0;

  /* FPU settings ------------------------------------------------------------*/
  #if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
    SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2));  /* set CP10 and CP11 Full Access */
  #endif

  /* Configure the Vector Table location -------------------------------------*/
#if defined(USER_VECT_TAB_ADDRESS)
  SCB->VTOR = VECT_TAB_BASE_ADDRESS | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */
#endif /* USER_VECT_TAB_ADDRESS */

  /* 设置时钟 */
  /* 
   * P163-->RCC_CR
   * P185-->RCC_APB1ENR 28 PWR EN
   * P147-->PWR_CR 15:14 VOS
   * P100-->FLASH_ACR
   * P81-->Table12 168MHz<-->5WS
   * P167-->RCC_CFGR
   * P228-->RCC_PLLCFGR
   */
  RCC->CR |= (1 << 16);
  // while (!(RCC->CR & (1 << 17))); // 等待HSE就绪
  // 等待HSE就绪 避免卡死
  timeout = HSE_STARTUP_TIMEOUT;
  while (!(RCC->CR & RCC_CR_HSERDY) && timeout--) {
    if (timeout == 0) { // 如果超时
        // HSE启动失败，切换到HSI
        RCC->CR |= RCC_CR_HSION; // 启用内部高速时钟（HSI）
        while (!(RCC->CR & RCC_CR_HSIRDY)); // 等待HSI就绪
        return;
    }
  }
  RCC->APB1ENR |= RCC_APB1ENR_PWREN; // 启用电源时钟
  // 启用预取指、指令缓存、数据缓存，设置延迟为5个周期
  FLASH->ACR = FLASH_ACR_PRFTEN | FLASH_ACR_ICEN | FLASH_ACR_DCEN | (5 << FLASH_ACR_LATENCY_Pos);
  RCC->CFGR &= ~(RCC_CFGR_HPRE_Msk); // 清除AHB预分频位
  RCC->CFGR |= RCC_CFGR_HPRE_DIV1; // 设置AHB预分频为1
  RCC->CFGR &= ~(RCC_CFGR_PPRE1_Msk); // 清除APB1预分频位
  RCC->CFGR |= RCC_CFGR_PPRE1_DIV4; // 设置APB1预分频为4
  RCC->CFGR &= ~(RCC_CFGR_PPRE2_Msk); // 清除APB2预分频位
  RCC->CFGR |= RCC_CFGR_PPRE2_DIV2; // 设置APB2预分频为2
  // 设置PLL参数，选择HSE作为PLL时钟源
  RCC->PLLCFGR = (PLL_M << RCC_PLLCFGR_PLLM_Pos) |
                (PLL_N << RCC_PLLCFGR_PLLN_Pos) |
                (((PLL_P-1)/2) << RCC_PLLCFGR_PLLP_Pos) |
                (PLL_Q << RCC_PLLCFGR_PLLQ_Pos) |
                RCC_PLLCFGR_PLLSRC_HSE;
  RCC->CR |= RCC_CR_PLLON; // 启用PLL
  // while (!(RCC->CR & RCC_CR_PLLRDY)); // 等待PLL就绪
  // 等待PLL就绪 避免卡死
  timeout = PLL_STARTUP_TIMEOUT;
  while (!(RCC->CR & RCC_CR_PLLRDY) && timeout--) {
    if (timeout == 0) { // 如果超时
        // PLL启动失败，切换到HSI
        RCC->CR |= RCC_CR_HSION; // 启用内部高速时钟（HSI）
        while (!(RCC->CR & RCC_CR_HSIRDY)); // 等待HSI就绪
        return;
    }
  }
  RCC->CFGR &= ~(RCC_CFGR_SW_Msk); // 清除系统时钟源选择位
  RCC->CFGR |= RCC_CFGR_SW_PLL; // 选择PLL作为系统时钟源
  // while (!(RCC->CFGR & RCC_CFGR_SWS_PLL)); // 等待PLL被选为系统时钟
  timeout = PLL_STARTUP_TIMEOUT;
  while (!(RCC->CR & RCC_CFGR_SWS_PLL) && timeout--) {
    if (timeout == 0) { // 如果超时
        // PLL启动失败，切换到HSI
        RCC->CR |= RCC_CR_HSION; // 启用内部高速时钟（HSI）
        while (!(RCC->CR & RCC_CR_HSIRDY)); // 等待HSI就绪
        return;
    }
  }
}
